package com.haidechizi.tree.search;

public class Node {

    private int value;
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public void addNode(Node node) {
        if (node == null) {
            return;
        }
        if (node.value < this.value) {
            if (this.left != null) {
                this.left.addNode(node);
            } else {
                this.left = node;
                return;
            }
        } else {
            if (this.right == null) {
                this.right = node;
                return;
            } else {
                this.right.addNode(node);
            }
        }
    }

    public void midShow() {
        if (this.left != null) {
            this.left.midShow();
        }
        System.out.println(this.value);
        if (this.right != null) {
            this.right.midShow();
        }
    }

    public void frontShow() {
        System.out.println(this.value);
        if (this.left != null) {
            this.left.frontShow();
        }
        if (this.right != null) {
            this.right.frontShow();
        }
    }

    public void afterShow() {
        if (this.left != null) {
            this.left.afterShow();
        }
        if (this.right != null) {
            this.right.afterShow();
        }
        System.out.println(this.value);
    }

    public Node searchNode(int i) {
        if (this.value == i) {
            return this;
        }
        // 查找左子树
        if (i < this.value) {
            if (this.left == null) {
                return null;
            }
            return this.left.searchNode(i);

            // 查找右子树
        } else {
            if (this.right == null) {
                return null;
            }
            return this.right.searchNode(i);
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                ", left=" + left +
                ", right=" + right +
                '}';
    }

    public Node searchParent(int value) {
        if ((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) {
            return this;
        }
        if (this.value > value && this.left != null) {
            return this.left.searchParent(value);
        } else if (this.value <= value && this.right != null) {
            return this.right.searchParent(value);
        }
        return null;
    }
}
